using DotNetExtensions.Core.Http.Events;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace DotNetExtensions.Core.Http
{
    public partial class RestfulHttpRequest : IRestfulHttpReqeust, IDisposable
    {
        public void Cancel()
        {
            if (Cancellation.ContainsKey(RequestId)) Cancellation[RequestId].Cancel();
        }

        private CancellationToken CreateCancellationToken()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            if (!Cancellation.ContainsKey(RequestId)) Cancellation.Add(RequestId, cancellationTokenSource);

            return cancellationToken;
        }

        private void RemoveCancellationToken()
        {
            if (!Cancellation.ContainsKey(RequestId)) Cancellation.Remove(RequestId);
        }
        
        public HttpResponse Send(string url, Method method = Method.GET)
        {
            return Send(url, new HttpRequest(), method);
        }

        public async Task SendAsync(string url, Method method = Method.GET)
        {
            await SendAsync(url, new HttpRequest(), method);
        }

        public async Task SendAsync(string url, HttpRequest content, Method method = Method.POST)
        {
            var e = new RequestTransferArgs(RequestId);
            e.Content = content.Content;
            Before?.Invoke(url, e);
            if (e.Cancel)
            {
                await Task.Factory.StartNew(() =>
                {
                    Completed?.Invoke(url, e);
                });
            }
            else
            {
                await Task.Factory.StartNew(() =>
                {
                    var response = Send(url, content, method);
                    
                    e.Successed = response.OK;

                    Completed?.Invoke(url, e);
                });
            }
        }
    }
}
